package com.deyuanyun.pic.ctrl.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.deyuanyun.pic.common.cache.TempStoreDataSupport;
import com.deyuanyun.pic.common.util.CommonUtil;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.RequestUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.ctrl.app.domain.CtrlLoginLog;
import com.deyuanyun.pic.ctrl.app.domain.CtrlResult;
import com.deyuanyun.pic.ctrl.app.domain.PipefromToDto;
import com.deyuanyun.pic.ctrl.app.enumeration.CtrlAppCode;
import com.deyuanyun.pic.ctrl.app.enumeration.ImgCustomType;
import com.deyuanyun.pic.ctrl.app.service.CtrlService;
import com.deyuanyun.pic.ctrl.service.OperationPlanService;
import com.deyuanyun.pic.settings.controller.dto.MyFileVO;
import com.deyuanyun.pic.settings.controller.dto.SMSMessageVO;
import com.deyuanyun.pic.settings.service.base.UploadService;
import com.deyuanyun.pic.settings.support.utils.SMSUtils;
import com.deyuanyun.pic.settings.task.Pool;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jerry
 * @Description 腐蚀控制app前台控制器
 * @date 2016-09-20
 */
@Controller
@RequestMapping("/ctr/app")
public class CtrlController {

    private Logger logger = LogManager.getLogger(this.getClass());

    @Resource
    private CtrlService ctrlService;


    @Resource
    private OperationPlanService operationPlanService;//运行计划service

    @Resource
    private UploadService uploadService;

    @Value("${File_Server_Path}")
    String fileServerPath;//文件服务器地址

    @RequestMapping("/getUserName")
    @ResponseBody
    public void getUserName(String Param, HttpServletResponse rep) {
        CtrlResult ctrlResult = new CtrlResult();
        JSONObject obj = JSON.parseObject(Param);
        if (ObjectUtil.isEmptyAll(obj)) {
            sendAppMessage(ctrlResult, CtrlAppCode.PARAMETER_FAIL.getCode(), CtrlAppCode.PARAMETER_FAIL.getLabel(), rep);
            return;
        }
        String account = obj.getString("Account").trim();
        try {
            CtrlResult result = ctrlService.getUserName(account);
            AjaxResponse.sendText(rep, JSON.toJSONString(result));

        } catch (Exception e) {
            logger.error(e);
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), rep);
        }

    }


    @RequestMapping("/loginApp")
    @ResponseBody
    public void login(String Param, HttpServletRequest request, HttpServletResponse rep) {
        CtrlResult ctrlResult = null;
        try {
            ctrlResult = ctrlService.login(Param, request);
            AjaxResponse.sendText(rep, JSON.toJSONString(ctrlResult));
        } catch (Exception e) {
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), rep);

            CtrlLoginLog loginLog = JSON.parseObject(Param, CtrlLoginLog.class);
            loginLog.setId(CommonUtil.getUUID());
            loginLog.setCreateDate(new Date());
            loginLog.setState(1);
            ctrlService.insertErrLog(loginLog);

            logger.error(e);
        }

    }

    /**
     * 发送验证码
     *
     * @param phone
     * @param response
     * @throws Exception
     */
    @RequestMapping("/getVerifyCode")
    @ResponseBody
    public void sendLoginCaptchaSms(String phone, HttpServletResponse response) throws Exception {
        Asserts.assertTrue(org.apache.commons.lang.StringUtils.isNotEmpty(phone), "手机号码不能为空");
        phone = phone.trim();
        Asserts.assertTrue(StringUtils.isMobile(phone), "手机号码非法");

        String p1 = TempStoreDataSupport.pullData("sms_" + phone);
        Asserts.assertTrue(org.apache.commons.lang.StringUtils.isBlank(p1), "发送频率过快，请稍后重试");

        String sms = SMSUtils.makeLoginCaptchaMsg(phone);
        SMSMessageVO vo = new SMSMessageVO();
        vo.setMessage(sms);
        vo.setType("login");
        vo.setPhone(phone);
        Pool.SMS_QUEUE.put(vo);
        CtrlResult ctrlResult = new CtrlResult();
        sendAppMessage(ctrlResult, CtrlAppCode.CAPTCHA_SUCCESS.getCode(), CtrlAppCode.CAPTCHA_SUCCESS.getLabel(), response);
    }


    @RequestMapping("/logoutApp")
    @ResponseBody
    public void getlogputApp(String Param, HttpServletRequest request, HttpServletResponse rep) {
        CtrlResult ctrlResult = new CtrlResult();
        sendAppMessage(ctrlResult, CtrlAppCode.SUCCESS.getCode(), CtrlAppCode.SUCCESS.getLabel(), rep);
        request.getSession().removeAttribute("App_User_");
        // SecurityUtils.removeUser(request);
        // org.apache.shiro.SecurityUtils.getSubject().logout();

    }

    //获取配置
    @RequestMapping("/getConfigs")
    @ResponseBody
    public void getConfigs(String Param, HttpServletResponse response) {
        // this.checkUser(Param,response);
        CtrlResult ctrlResult = new CtrlResult();
        try {
            ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
            ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
            Map<String, Object> map = ctrlService.getConfigs();
            ctrlResult.setResult(map);
            AjaxResponse.sendText(response, JSON.toJSONString(ctrlResult));
        } catch (Exception e) {
            logger.error(e);
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), response);
        }
    }


    //获取基础设施
    @RequestMapping("/getInfrastructures")
    @ResponseBody
    public void getInfrastructures(String Param, HttpServletResponse response) {
        // this.checkUser(Param,response);
        CtrlResult ctrlResult = new CtrlResult();
        try {
            ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
            ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
            Map<String, Object> map = ctrlService.getInfrastructures();
            ctrlResult.setResult(map);
            AjaxResponse.sendText(response, JSON.toJSONString(ctrlResult));
        } catch (Exception e) {
            logger.error(e);
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), response);
        }

    }

    @RequestMapping("/getPlans")
    @ResponseBody
    public void getPlans(String Param, HttpServletResponse response) {
        // this.checkUser(Param,response);
        CtrlResult ctrlResult = new CtrlResult();
        try {
            ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
            ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
            Map<String, Object> map = operationPlanService.getPlans();
            ctrlResult.setResult(map);
            String result = JSON.toJSONString(ctrlResult, SerializerFeature.DisableCircularReferenceDetect);
            AjaxResponse.sendText(response, result);
        } catch (Exception e) {
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), response);
            logger.error(e);
        }

    }

    @Deprecated
    @RequestMapping("/reportException")
    @ResponseBody
    public void reportException(String Param, HttpServletResponse response) {
        CtrlResult ctrlResult = new CtrlResult();
        try {
            ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
            ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
            ctrlService.reportException(Param);
            String result = JSON.toJSONString(ctrlResult);
            AjaxResponse.sendText(response, result);
        } catch (Exception e) {
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), response);
            logger.error(e);
        }

    }

    @Deprecated
    @RequestMapping("/getFromToById")
    @ResponseBody
    public void getFromToById(String Param, HttpServletResponse response) {
        CtrlResult ctrlResult = new CtrlResult();
        try {
            ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
            ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
            PipefromToDto fromTo = ctrlService.queryPipeFromToById(Param);
            if (ObjectUtil.isNotNullEmpty(fromTo)) {
                ctrlResult.setResult(fromTo);
            }
            String result = JSON.toJSONString(ctrlResult);
            AjaxResponse.sendText(response, result);
        } catch (Exception e) {
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), response);
              logger.error(e);
        }

    }


    @RequestMapping("/getLocationByName")
    @ResponseBody
    public void getLocationByName(String Param, HttpServletResponse response) {
        CtrlResult ctrlResult = new CtrlResult();
        try {
            ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
            ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
            Map map = ctrlService.queryPipePlaceByName(Param);
            ctrlResult.setResult(map);
            String result = JSON.toJSONString(ctrlResult);
            AjaxResponse.sendText(response, result);
        } catch (Exception e) {
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), response);
             logger.error(e);
        }

    }

    @RequestMapping("/postForm")
    @ResponseBody
    public void postForm(String Param, HttpServletResponse response) {
        CtrlResult ctrlResult = new CtrlResult();
        try {
            ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
            ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
            ctrlService.postForm(Param);
            String result = JSON.toJSONString(ctrlResult);
            AjaxResponse.sendText(response, result);
        } catch (Exception e) {
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), response);
            logger.error("<======提交表单失败==========>", e);
        }

    }

    @RequestMapping("/followDevice")
    @ResponseBody
    public void settingPlan(String Param, HttpServletResponse response) {
        CtrlResult ctrlResult = new CtrlResult();
        try {
            ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
            ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
            ctrlService.settingPlan(Param);
            String result = JSON.toJSONString(ctrlResult);
            AjaxResponse.sendText(response, result);
        } catch (Exception e) {
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), response);
            logger.error(e);
        }

    }


    @RequestMapping("/getFollowDevice")
    @ResponseBody
    public void getPlanSetting(String Param, HttpServletResponse response) {
        CtrlResult ctrlResult = new CtrlResult();
        try {
            ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
            ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
            Map map = ctrlService.getPlanSetting(Param);
            ctrlResult.setResult(map);
            String result = JSON.toJSONString(ctrlResult);
            System.out.println(result);
            AjaxResponse.sendText(response, result);
        } catch (Exception e) {
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), response);
            logger.error(e);
        }

    }


    @RequestMapping("/updateFavourites")
    @ResponseBody
    public void updateFavourites(String Param, HttpServletResponse response) {
        CtrlResult ctrlResult = new CtrlResult();
        try {
            ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
            ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
            ctrlService.updateFavourites(Param);
            String result = JSON.toJSONString(ctrlResult);
            AjaxResponse.sendText(response, result);
        } catch (Exception e) {
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), response);
            logger.error(e);
        }

    }


    @RequestMapping("/getFavourites")
    @ResponseBody
    public void getFavourites(String Param, HttpServletResponse response) {
        CtrlResult ctrlResult = new CtrlResult();
        try {
            ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
            ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
            Map<String, Object> map = ctrlService.getFavourites(Param);
            if(map != null){
                Map<String,Object> map1 = new HashMap<String, Object>();
                map1.put("favourite",map);
                ctrlResult.setResult(map1);
            }
            String result = JSON.toJSONString(ctrlResult);
            AjaxResponse.sendText(response, result);
        } catch (Exception e) {
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), response);
              logger.error(e);
        }

    }

    @RequestMapping("/editFavourites")
    @ResponseBody
    public void editFavourites(String Param, HttpServletResponse response) {
        CtrlResult ctrlResult = new CtrlResult();
        try {
            ctrlResult.setCode(CtrlAppCode.SUCCESS.getCode());
            ctrlResult.setMsg(CtrlAppCode.SUCCESS.getLabel());
            ctrlService.editFavourites(Param);
            String result = JSON.toJSONString(ctrlResult);
            AjaxResponse.sendText(response, result);
        } catch (Exception e) {
            sendAppMessage(ctrlResult, CtrlAppCode.SERVICE_FAIL.getCode(), CtrlAppCode.SERVICE_FAIL.getLabel(), response);
            logger.error(e);
        }

    }


    /**
     * 上传附件
     *
     * @param multipartFiles
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/uploadAppFile")
    @ResponseBody
    public void saveUploadFile(@RequestParam(value = "file", required = false) MultipartFile[] multipartFiles, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map param = RequestUtil.parseRequestParamToHashMap(request);
        String businessId = param.get("id").toString();//关联ID
        MyFileVO fileVO = new MyFileVO();
        CtrlResult result = new CtrlResult();
        fileVO.setType(ImgCustomType.APPUPLOAD_IMAGE.toString());


        fileVO.setBusinessId(businessId);
        if (multipartFiles == null || multipartFiles.length == 0) {
            sendAppMessage(result, CtrlAppCode.UPLOAD_FAIL.getCode(), CtrlAppCode.UPLOAD_FAIL.getLabel(), response);
            return;
        }
        String res = uploadService.saveStorageFile(multipartFiles[0], fileVO);
        String id = org.apache.commons.lang.StringUtils.substringBetween(res, "[", "]");
        String path = org.apache.commons.lang.StringUtils.substringBetween(res, "{", "}");
        if (org.apache.commons.lang.StringUtils.isNotBlank(path)) {
            result.setCode(CtrlAppCode.UPLOAD_SUCCESS.getCode());
            result.setMsg(CtrlAppCode.UPLOAD_SUCCESS.getLabel());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("Url", fileServerPath+path);
            map.put("Id",id);
            result.setResult(map);
            AjaxResponse.sendText(response, JSON.toJSONString(result));
        }

    }


    /**
     * 验证是否是合法用户
     *
     * @param Param
     * @param rep
     */
    private void checkUser(String Param, HttpServletResponse rep) {
        JSONObject obj = JSON.parseObject(Param);
        Map mapMarks = new HashMap();
        if (ObjectUtil.isEmptyAll(obj)) {
            sendAppMessage(mapMarks, CtrlAppCode.PARAMETER_FAIL.getCode(), CtrlAppCode.PARAMETER_FAIL.getLabel(), rep);
            return;
        }
        String userId = obj.getString("userID");
        if (userId == null) {
            sendAppMessage(mapMarks, CtrlAppCode.PARAMETER_FAIL.getCode(), CtrlAppCode.PARAMETER_FAIL.getLabel(), rep);
            return;
        }
        return;
    }

    /**
     * 封装向app发送消息函数
     *
     * @param obj   对象
     * @param code  code编码
     * @param label 对应消息
     */
    private void sendAppMessage(Object obj, String code, String label, HttpServletResponse rep) {
        if (obj instanceof Map) {
            ((Map) obj).put("Code", code);
            ((Map) obj).put("Msg", label);
            AjaxResponse.sendText(rep, JSON.toJSONString(obj));
            return;
        }
        if (obj instanceof CtrlResult) {
            ((CtrlResult) obj).setCode(code);
            ((CtrlResult) obj).setMsg(label);
            AjaxResponse.sendText(rep, JSON.toJSONString(obj));
        }
    }


}

